package github.sf.fw.tools.serializer;

import github.sf.fw.utils.RefUtils;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * ImplContainer
 *
 * @author zhoup
 * @since 2023/4/14
 */
public class ImplContainer {
    private final Map<String, String> implAndClassName = new LinkedHashMap<>();

    public static ImplContainer getInstance() {
        return InnerClassForSingleton.INSTANCE;
    }

    public void register(String implType, String implClass) {
        implAndClassName.put(implType, implClass);
    }

    public String getImplClass(String implType) {
        return implAndClassName.get(implType);
    }

    @SuppressWarnings(value = {"unchecked"})
    public Class<? extends ImplementMarker> resolveClass(String implType) {
        if (implType == null || "".equals(implType)) {
            throw new IllegalArgumentException("约束类型不能为空");
        }
        String implClass = getImplClass(implType);
        Objects.requireNonNull(implClass, "约束暂无" + implType + "类型的实现类");
        try {
            return (Class<? extends ImplementMarker>) Class.forName(implClass);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public ImplementMarker createObject(String constraintType) {
        if (constraintType == null || "".equals(constraintType)) {
            throw new IllegalArgumentException("约束类型为空，无法查找具体的实现类");
        }
        String implClass = getImplClass(constraintType);
        if (implClass == null || "".equals(implClass)) {
            throw new IllegalArgumentException("暂未找到" + constraintType + "的实现类");
        }
        return RefUtils.newInstance(implClass);
    }

    private static class InnerClassForSingleton {
        private final static ImplContainer INSTANCE = new ImplContainer();
    }
}
